package walletService

import (
	"errors"
	"github.com/spf13/cast"
	"hc_server/routers/models"
	"math"
)

type Wallet struct {
	AgentId  int
	PageNum  int
	PageSize int

	Ids            string  //AgentApplyWithdrawalCache的id集合
	WithdrawalTime string  //提现具体月份
	AfterAmount    float32 //提现总金额
	BankName       string  //提现银行名称
	BankNo         string  //提现银行卡号码
}

// WalletList 钱包明细
func (w *Wallet) WalletList() (any, error) {
	return models.WalletList(w.AgentId, w.PageNum, w.PageSize)
}

// WalletApplyList 申请提现列表
func (w *Wallet) WalletApplyList() (any, error) {
	return models.WalletApplyList(w.AgentId)
}

// WalletWithdrawalRecord 提现记录
func (w *Wallet) WalletWithdrawalRecord() (any, error) {
	return models.WalletWithdrawalRecord(w.AgentId)
}

// WalletWithdrawal 立即提现
func (w *Wallet) WalletWithdrawal() error {
	db := models.Begin()
	//获取可提取金额列表数据
	caches, err := models.AgentApplyWithdrawalCacheGet(w.Ids)
	if err != nil {
		db.Rollback()
		return err
	}

	var amount float32
	for _, c := range caches {
		//判断交易利润和订单是否存在，并返回可提取金额和修改交易利润状态为2已提取
		beginAmount, err := models.AgentIncomeLogExist(c.OrderIds)
		if err != nil {
			db.Rollback()
			return err
		}

		amount += beginAmount
	}

	expected := float32(math.Round(float64(amount)*0.91*100) / 100)
	after := float32(math.Round(float64(w.AfterAmount)*100) / 100)
	if expected != after {
		db.Rollback()
		return errors.New("系统错误")
	}

	err = models.AgentWithdrawalLogCreate(&models.AgentWithdrawalLog{
		AgentId:     w.AgentId,
		CacheIds:    w.Ids,
		BeginAmount: cast.ToFloat64(amount),
		TaxAmount:   cast.ToFloat64(amount * 0.09),
		AfterAmount: cast.ToFloat64(w.AfterAmount),
		BankName:    w.BankName,
		BankNo:      w.BankNo,
	})
	if err != nil {
		db.Rollback()
		return err
	}

	db.Commit()
	return nil
}
